package com.company.project.modular.standard.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.company.project.core.base.controller.BaseController;
import com.company.project.core.base.tips.ErrorTip;
import com.company.project.core.base.tips.SuccessTip;
import com.company.project.core.log.LogObjectHolder;
import com.company.project.modular.system.service.IDocService;
import com.company.project.modular.system.service.IStandardService;
import com.company.project.modular.system.model.Doc;
import com.company.project.modular.system.model.Standard;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.script.ScriptException;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 控制器
 *
 * @author fengshuonan
 * @Date 2018-11-03 14:04:25
 */
@Controller
@RequestMapping("/doc")
public class DocController extends BaseController {

    /*private String PREFIX = "/standard/doc/";*/
    private String PREFIX = "/standard/standard/";

    @Reference
    private IDocService docService;
    @Reference
    private IStandardService standardService;

    private ServletContext context;

    /**
     * 跳转到首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "doc.html";
    }

    /**
     * 跳转到添加
     */
    @RequestMapping("/doc_add")
    public String docAdd() {
        return PREFIX + "doc_add.html";
    }

    /**
     * 跳转到修改
     */
    @RequestMapping("/doc_update/{docId}")
    public String docUpdate(@PathVariable Integer docId, Model model) {
        Doc doc = docService.selectById(docId);
        model.addAttribute("item",doc);
        LogObjectHolder.me().set(doc);
        return PREFIX + "doc_edit.html";
    }

    /**
     * 获取列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(String condition) {
        return docService.selectList(null);
    }

    /**
     * 新增文件上传
     * id是标准物质表的id
     */
    @RequestMapping(value = "/addDoc",method = RequestMethod.POST)
    @ResponseBody
    public Object addDoc(Doc doc,Standard standard,String id,BindingResult bindingResult, @RequestParam("file") MultipartFile file)  {
        /* 保存附件表*/
            if (file.isEmpty()) {
                System.out.println("文件为空");
                return new ErrorTip(0,"文件为空");
            }else{
                String contentType = file.getContentType();
                String fileName = file.getOriginalFilename();
                long filesize = file.getSize();
                Double docsize = Double.valueOf(filesize);
                String classpath = this.getClass().getResource("/").getPath().replaceFirst("/", "");
                String docRoot0 = classpath.replaceAll("WEB-INF/classes/", "");
                String docRoot = docRoot0 + "static/";
                File destFile = new File(docRoot,fileName);
                try {
                    file.transferTo(destFile); //保存文件
                } catch (IOException e) {
                    e.printStackTrace();
                }
                doc.setDocType(contentType);
                doc.setDocSize(docsize);
                doc.setDocName(fileName);
                //得到long类型当前时间
                long l = System.currentTimeMillis(); //new日期对象
                Date date = new Date(l); //转换提日期输出格式
                doc.setDocDate(date);
                String filePath=docRoot + fileName;
                doc.setDocPath(filePath);
                docService.insert(doc);
                /*根据标准物质表id查询一条记录并且更新standard表,将文件表的编号存进去*/
                standard = standardService.findAll(id);
                /*查找文件表最大的id*/
                String docIdList = docService.findById();
                standard.setDocId(Integer.valueOf(docIdList));
                standardService.updateById(standard);
                return new SuccessTip();
            }
    }


    /**
     * 新增
     */
    @RequestMapping(value = "/add" ,method = RequestMethod.POST)
    /*@ResponseBody*/
    public Object add(Doc doc, Standard standard, BindingResult bindingResult, @RequestParam("file") MultipartFile file) throws ScriptException, FileNotFoundException {
        /*保存StandardId*/
        //得到long类型当前时间
        long l = System.currentTimeMillis(); //new日期对象
        Date date = new Date(l); //转换提日期输出格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String createdate = dateFormat.format(date);
        standard.setStandardId(createdate);
        /* 保存附件表*/
        try {
            if (file.isEmpty()) {
                return "文件为空";
            }else {
                String contentType = file.getContentType();
                String fileName = file.getOriginalFilename();
                long filesize = file.getSize();
                Double docsize = Double.valueOf(filesize);

                String classpath = this.getClass().getResource("/").getPath().replaceFirst("/", "");
                String docRoot0 = classpath.replaceAll("WEB-INF/classes/", "");
                String docRoot = docRoot0 + "static/upload/";
                File destFile = new File(docRoot,fileName);
                file.transferTo(destFile); //保存文件

                doc.setDocType(contentType);
                doc.setDocSize(docsize);
                doc.setDocName(fileName);
                doc.setDocDate(date);
                String filePath=docRoot + fileName;
                doc.setDocPath(filePath);
                docService.insert(doc);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        int docId = doc.getId();
        standard.setDocId(docId);

        /*保存StandardLabel*/
        String maxNumber = standardService.findByMaxNumber().get(0).getStandardLabel();
        /*String maxNumber = "50001";*/  /*当表里面没有任何一条数据的时候，应该做一个查询，再做一个判断，此处先省略*/
        if("null".equals(maxNumber)){
            maxNumber = null;
            int a = 50001;
            String number = String.valueOf(a);
            standard.setStandardLabel(number);
        }else {
            int a = Integer.valueOf(maxNumber)+1;
            String number = String.valueOf(a);
            standard.setStandardLabel(number);
        }
        /*保存StandardCode*/
        String standardCode =  standard.getStandardId() + standard.getStandardLabel();
        standard.setStandardCode(standardCode);
        standardService.insert(standard);
        return new SuccessTip();
    }

    //文件下载
    @RequestMapping("/download")
    @ResponseBody
    public Object download(@RequestParam Integer id, HttpServletRequest request, HttpServletResponse response, HttpServletResponse res) {
        try {
            /*根据standId查询docId，根据docId查询docId表*/
            int docId = standardService.findByDocId(id);
            Doc doc = docService.findByAll(docId);
            /*获取文件表的信息*/
            String docName =  doc.getDocName();// 设置文件名
            if(StringUtils.isNotEmpty(docName)) {
                //返回文件路径
                String path = "/static/" + docName;
                return new ErrorTip(200, path);
            }else{
                return new ErrorTip(10, "文件不存在");
            }
        }catch (Exception e){
            return new ErrorTip(0,"文件下载错误");
        }
    }

    /**
     * 删除
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer docId) {
        docService.deleteById(docId);
        return SUCCESS_TIP;
    }

    /**
     * 修改
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(Doc doc) {
        docService.updateById(doc);
        return SUCCESS_TIP;
    }

    /**
     * 详情
     */
    @RequestMapping(value = "/detail/{docId}")
    @ResponseBody
    public Object detail(@PathVariable("docId") Integer docId) {
        return docService.selectById(docId);
    }


    public ServletContext getContext() {
        return context;
    }

    public void setContext(ServletContext context) {
        this.context = context;
    }
}
